package com.dinglian.ots.controller.brand;

import com.alibaba.fastjson.JSONObject;
import com.dinglian.ots.common.HttpRequest;
import com.dinglian.ots.common.ToolUtils;
import com.dinglian.ots.exception.GlobalException;
import com.dinglian.ots.result.CodeMsg;
import com.dinglian.ots.result.Result;
import com.dinglian.ots.service.BrandService;
import com.dinglian.ots.vo.brand.*;
import com.dinglian.ots.vo.buyer.InviteVo;
import com.dinglian.ots.vo.buyer.SearchBuyerVo;
import com.dinglian.ots.vo.order.BuyerOrderVo;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * @author wangbo
 */
@Slf4j
@RestController
@Api(value = "/brand", tags = "品牌模块")
@RequestMapping("/brand/")
@CrossOrigin
public class BrandController {

    @Autowired
    private BrandService brandService;

    @Value("${brandUrl}")
    private String brandUrl;

    @Value("${pic.url}")
    private String url;

    @ApiOperation("获取所有品牌")
    @GetMapping("getBrandList")
    public Result getBrandList(@RequestParam(value = "userId") Integer userId,
                               @RequestParam(value = "categoryId", required = false) Integer categoryId,
                               @RequestParam(value = "keyword", required = false) String keyword,
                               @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                               @RequestParam(value = "pageSize", defaultValue = "60") Integer pageSize) {
        PageInfo<BrandVo> brandList = new PageInfo<>();
        try {
            brandList = brandService.getBrandList(userId, categoryId, keyword, pageNum, pageSize);
        } catch (GlobalException e) {
            return Result.error(e.getCm());
        }catch (Exception e) {
            e.printStackTrace();
            return Result.error(CodeMsg.SERVER_ERROR);
        }
        return Result.success(brandList);
    }

    @ApiOperation(value = "获取TOP榜单", notes = "pageNum默认为1 pageSize默认为5 sort 1-升序2-降序 默认升序 ")
    @GetMapping("getTopBillboard")
    public Result getTopBillboard(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                  @RequestParam(value = "pageSize", defaultValue = "100") Integer pageSize,
                                  @RequestParam(value = "sort", defaultValue = "2") Integer sort,
                                  @RequestParam(value = "categoryId", required = false) Integer categoryId) {
        Set<TopBrandVo> brandList = new LinkedHashSet<>();
        try {
            brandList = brandService.getTopBillboard(pageNum, pageSize, sort, categoryId);
        } catch (GlobalException e) {
            return Result.error(e.getCm());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(CodeMsg.SERVER_ERROR);
        }
        return Result.successWithUrl(brandList, url);
    }

    @ApiOperation("获取推荐TOP品牌")
    @GetMapping("getRecommendTopBrand")
    public Result getRecommendTopBrand(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                    @RequestParam(value = "pageSize", defaultValue = "100") Integer pageSize,
                                    @RequestParam(value = "categoryId", required = false) Integer categoryId) {
        PageInfo<BrandTopVo> brandList = new PageInfo<>();
        try {
            brandList = brandService.getRecommendTopBrand(pageNum, pageSize, categoryId);
        } catch (GlobalException e) {
            return Result.error(e.getCm());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(CodeMsg.SERVER_ERROR);
        }
        return Result.successWithUrl(brandList.getList(), url);
    }

    @ApiOperation("获取推荐品牌")
    @GetMapping("getRecommendBrand")
    public Result getRecommendBrand(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                    @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                    @RequestParam(value = "categoryId", required = false) Integer categoryId) {
        PageInfo<BrandVo> brandList = new PageInfo<>();
        try {
            brandList = brandService.getRecommendBrand(pageNum, pageSize, categoryId);
        } catch (GlobalException e) {
            return Result.error(e.getCm());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(CodeMsg.SERVER_ERROR);
        }
        return Result.successWithUrl(brandList.getList(), url);
    }

    @ApiOperation("获取品牌详情")
    @GetMapping("getBrandDetail")
    public Result getBrandDetail(@RequestParam(value = "brandId") Integer brandId,
                                 @RequestParam(value = "userId", required = false) Integer userId) {
        BrandDetailVo brandInfoVo = new BrandDetailVo();
        try {
            brandInfoVo = brandService.getBrandDetail(userId, brandId);
        } catch (GlobalException e) {
            return Result.error(e.getCm());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(CodeMsg.SERVER_ERROR);
        }
        return Result.success(brandInfoVo);
    }

    @ApiOperation("申请通过/驳回")
    @GetMapping("agreeIntention")
    public Result agreeIntention(@RequestParam(value = "relationId") Integer relationId,
                                 @RequestParam(value = "isPass") boolean isPass) {
        try {
            AgreeVo agreeVo = new AgreeVo();
            agreeVo.setPass(isPass);
            agreeVo.setRelationId(relationId);
            brandService.agreeIntention(agreeVo);
        } catch (GlobalException e) {
            return Result.error(e.getCm());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(CodeMsg.SERVER_ERROR);
        }
        return Result.successNoData();

    }

    @ApiOperation("品牌信息同步")
    @GetMapping("synchronizeBrandInfo")
    public Result synchronizeBrandInfo(@RequestParam(value = "phone", required = false) String phone,
                                       @RequestParam(value = "mail", required = false) String mail) {
        try {
            String result = HttpRequest.sendPost(brandUrl, "phone=" + phone + "&mail=" + mail);
            result = ToolUtils.decodeUnicode(result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            brandService.synchronizeBrandInfo(jsonObject, phone);

        } catch (GlobalException e) {
            return Result.error(e.getCm());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(CodeMsg.SERVER_ERROR);
        }
        return Result.successNoData();
    }

    @ApiOperation("品牌信息录入")
    @PostMapping("updateBrandInfo")
    public Result updateBrandInfo(SaveBrandVo brandVo) {

        try {
            brandService.updateBrandInfo(brandVo);

        } catch (GlobalException e) {
            return Result.error(e.getCm());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(CodeMsg.SERVER_ERROR);
        }
        return Result.successNoData();
    }

    @ApiOperation("查询品牌信息")
    @GetMapping("getBrandInfo")
    public Result getBrandInfo(@RequestParam("brandId") Integer brandId) {
        BrandInfoVo brandInfoVo = new BrandInfoVo();
        try {
            brandInfoVo = brandService.getBrandInfo(brandId);

        } catch (GlobalException e) {
            return Result.error(e.getCm());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(CodeMsg.SERVER_ERROR);
        }
        return Result.success(brandInfoVo);
    }

    @ApiOperation("设置品牌订货规则")
    @PostMapping("setBrandOrderRule")
    public Result setBrandOrderRule(@RequestBody @Validated BrandRuleVo brandRuleVo) {
        try {
            brandService.setBrandOrderRule(brandRuleVo);
        } catch (GlobalException e) {
            return Result.error(e.getCm());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(CodeMsg.SERVER_ERROR);
        }
        return Result.successNoData();
    }


    @ApiOperation("获取品牌订货规则")
    @GetMapping("getBrandOrderRule")
    public Result getBrandOrderRule(@RequestParam("brandId") Integer brandId) {
        List<BrandRuleInfoVo> brandRuleInfoList = new ArrayList<>();
        try {
            brandRuleInfoList = brandService.getBrandOrderRule(brandId);
        } catch (GlobalException e) {
            return Result.error(e.getCm());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(CodeMsg.SERVER_ERROR);
        }
        return Result.success(brandRuleInfoList);
    }

    @ApiOperation("删除品牌订货规则")
    @GetMapping("deleteBrandOrderRule/{id}")
    public Result deleteBrandOrderRule(@PathVariable("id") Integer ruleId) {
        try {
            System.out.println("规则ID为" + ruleId);
            brandService.deleteBrandOrderRule(ruleId);

        } catch (GlobalException e) {
            return Result.error(e.getCm());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(CodeMsg.SERVER_ERROR);
        }
        return Result.successNoData();
    }


    @ApiOperation("查询选款单")
    @GetMapping("brandElectionOrder")
    public Result brandElectionOrder(@RequestParam("brandId") Integer brandId,
                                     @RequestParam("seasonId") Integer seasonId,
                                     @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                     @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize) {
        PageInfo<BuyerOrderVo> orderInfoVo = new PageInfo<>();
        try {
            orderInfoVo = brandService.brandElectionOrder(brandId, seasonId, pageNum, pageSize);
        } catch (GlobalException e) {
            return Result.error(e.getCm());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(CodeMsg.SERVER_ERROR);
        }
        return Result.successWithUrl(orderInfoVo, url);
    }


    @ApiOperation("导出选款单")
    @GetMapping("exportBrandElectionOrder")
    public void exportBrandElectionOrder(@RequestParam("userId") Integer userId, @RequestParam("seasonId") Integer seasonId, @RequestParam("brandId") Integer brandId, HttpServletResponse response) {

      /*  UserVo userVo = (UserVo) SecurityUtils.getSubject().getSession().getAttribute(Constant.SESSION_USER);
        System.out.println("session中是否有值"+userVo);
        Integer bId = brandService.selectBrandParentId(brandId);
        System.out.println("品牌的用户ID"+bId);
        if (userVo != null){
            Integer userId1 = userVo.getUserId();
            if (!userId1.equals(bId)){
                throw new GlobalException(CodeMsg.DONT_TOUCH_ME);
            }
        }else {
            throw new GlobalException(CodeMsg.USER_NOT_LOGIN);
        }*/

        brandService.exportBrandElectionOrder(userId, seasonId, brandId, response);

    }


    @ApiOperation("邀请买手")
    @PostMapping("inviteBuyer")
    public Result inviteBuyer(@RequestBody InviteVo inviteVo) {
        try {
            brandService.inviteBuyer(inviteVo);
        } catch (GlobalException e) {
            return Result.error(e.getCm());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(CodeMsg.SERVER_ERROR);
        }
        return Result.successNoData();
    }


    @ApiOperation("邀请买手列表")
    @GetMapping("inviteBuyerList")
    public Result inviteBuyerList(@RequestParam(value = "type",required = false)Integer type,
                                  @RequestParam(value = "brandId")Integer brandId,
                                  @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                  @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        PageInfo<SearchBuyerVo> list = new PageInfo<>();
        try {
            list = brandService.inviteBuyerList(brandId,type,pageNum,pageSize);
        } catch (GlobalException e) {
            return Result.error(e.getCm());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(CodeMsg.SERVER_ERROR);
        }
        return Result.success(list);
    }

    @ApiOperation("设置退换货率")
    @PostMapping("setReturnRatio")
    public Result setReturnRatio(@RequestBody ReturnRatioVo returnRatioVo) {
        try {
            brandService.setReturnRatio(returnRatioVo);
        } catch (GlobalException e) {
            return Result.error(e.getCm());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(CodeMsg.SERVER_ERROR);
        }
        return Result.successNoData();
    }


    @ApiOperation("设置不感兴趣")
    @GetMapping("setIsInterested")
    public Result setIsInterested(@RequestParam(value = "brandId") Integer brandId,
                                 @RequestParam(value = "storeId")Integer storeId) {
        try {
            brandService.setIsInterested(brandId,storeId);
        } catch (GlobalException e) {
            return Result.error(e.getCm());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(CodeMsg.SERVER_ERROR);
        }
        return Result.successNoData();
    }





}
